using System;
using System.Linq;
using Habanero.Base;
using Habanero.Base.Exceptions;
using Habanero.BO;

namespace FireStarterModeller.BO
{
    /// <summary>
    /// A <see cref="IBusinessObjectRule"/> that validates that a <see cref="DMRelationship"/>
    /// has at least one <see cref="DMProperty"/> and that this property has a Related Property.
    /// </summary>
    public class DMRelationshipMustHaveProperty : IBusinessObjectRule
    {
        private DMRelationship _dmRelationship;

//        public DMRelationshipMustHaveProperty(DMRelationship dmRelationship)
//        {
//            if (dmRelationship == null) throw new ArgumentNullException("dmRelationship");
//            _dmRelationship = dmRelationship;
//        }

        #region Implementation of IBusinessObjectRule

        /// <summary>
        /// Indicates whether the property value is valid against the rules
        /// </summary>
        /// <returns>
        /// Returns true if valid
        /// </returns>
        public bool IsValid()
        {
            throw new HabaneroApplicationException("The IsValid is no longer Valid you should use the IsValid(bo) method");
        }

        public bool IsValid(IBusinessObject bo)
        {
            _dmRelationship = (DMRelationship) bo;
            bool valid = _dmRelationship.OwnerClass != null && _dmRelationship.RelatedClass != null;
            if (!valid) return false;

            BusinessObjectCollection<DMRelationshipProperty> relationshipProperties = _dmRelationship.RelationshipProperties;
            if (relationshipProperties.Count == 0) return false;

            return relationshipProperties.All(relationshipProperty => relationshipProperty.OwnerProperty != null && relationshipProperty.RelatedProperty != null);
        }

        /// <summary>
        /// Returns the rule name
        /// </summary>
        public string Name
        {
            get { return "DMRelationshipMustHaveProperty"; }
        }

        /// <summary>
        /// Returns the error message for if the rule fails.
        /// </summary>
        public string Message
        {
            get { return "The Relationship '" + _dmRelationship + "' on Class '" + _dmRelationship.ClassDM + "' must have at least one Property"; }
        }
        /// <summary>
        /// The <see cref="P:Habanero.Base.IBusinessObjectRule.ErrorLevel" /> for this BusinessObjectRule e.g. Warning, Error. 
        /// </summary>
        public ErrorLevel ErrorLevel
        {
            get { return Habanero.Base.ErrorLevel.Error; }
        }

        #endregion
    }
}